import { getAttributesByType  } from './chart-observer-config.js';

// 创建模板
const chart_template = document.createElement("template");
chart_template.innerHTML = `
    <style>
        :host {
            display: block;
            width: 600px;
            height: 300px;
        }
        .chart-container {
             width: 100%;
            height: 100%;
            display: flex; /* 使用flex布局 */
            justify-content: center; /* 水平居中 */
            align-items: center; /* 垂直居中 */
        }
    </style>
    <div class="chart-container"></div>
`;


class ChartComponent extends HTMLElement {
    constructor() {
        super();
        // 创建 Shadow DOM
        const shadow = this.attachShadow({ mode: 'open' });
        // 克隆模板内容
        shadow.appendChild(chart_template.content.cloneNode(true));

        // 获取图表容器
        const chartDiv = shadow.querySelector('.chart-container');

        // 初始化定时器和图表实例
        this.timerId = null;
        this.chart = echarts.init(chartDiv);
    }

    connectedCallback() {
        const getAttributeWithDefault = (name, defaultValue) => this.getAttribute(name) || defaultValue;

        // key 生成规则：从第一个 - 后开始截取到 _ 前，- 转驼峰
        const normalizeKey = (attrName) => {
            const dashIndex = attrName.indexOf('-');
            if (dashIndex === -1) return attrName;
            const subStr = attrName.substring(dashIndex + 1, attrName.indexOf('_', dashIndex));
            return subStr.split('-').map((part, i) =>
                i === 0 ? part : part.charAt(0).toUpperCase() + part.slice(1)
            ).join('');
        };

        // 通用构造 config
        const buildConfig = (attrList) => {
            const cfg = {};
            attrList.forEach(([attrName, defaultValue]) => {
                // 处理属性值
                let val = getAttributeWithDefault(attrName, defaultValue);
                // 处理布尔值
                if (typeof defaultValue === 'boolean') {
                    val = this.getAttribute(attrName) !== null
                        ? this.getAttribute(attrName).toLowerCase() === 'true'
                        : defaultValue;
                }
                // 处理数字值
                if (typeof defaultValue === 'number') {
                    // 处理百分比值
                    val = parseFloat(val);
                }
                // 处理数组值
                if (attrName.endsWith('_array')) {
                    val = (val || '').split(',');
                }
                cfg[normalizeKey(attrName)] = val;
            });
            return cfg;
        };

        // 定义属性清单
        const titleAttrs = [
            ['title-text_text', '销售数据统计'],
            ['title-show_radio', true],
            ['title-left_slider', 'center'],
            ['title-top_slider', ''],
            ['title-right_slider', ''],
            ['title-bottom_slider', ''],
            ['title-textalign_select', 'center'],
            ['title-textstyle-color_colorpicker', '#333'],
            ['title-textstyle-fontsize_number', 18],
            ['title-textstyle-fontweight_select', 'bold'],
            ['title-subtext_text', '2023年度数据'],
            ['title-subtextstyle-color_colorpicker', '#666'],
            ['title-subtextstyle-fontsize_number', 14],
            ['title-subtextstyle-fontweight_select', 'normal'],
        ];
        const gridAttrs = [
            ['grid-left_slider', '10%'],
            ['grid-right_slider', '5%'],
            ['grid-bottom_slider', '15%'],
            ['grid-top_slider', '15%'],
            ['grid-containlabel_radio', true],
        ];
        const xAxisAttrs = [
            ['xaxis-nametextstyle-color_colorpicker', '#666'],
            ['xaxis-show_radio', true],
            ['xaxis-name_text', '商品类别'],
            ['xaxis-nametextstyle-fontsize_number', 12],
            ['xaxis-nametextstyle-fontstyle_select', 'normal'],
            ['xaxis-axislabel-color_colorpicker', '#666'],
            ['xAxis-data-textStyle-fontStyle_colorpicker', 'normal'],
            ['xaxis-axislabel-rotate_number', 0],
            ['xaxis-type_text', 'category'],
            ['xaxis-data_array', JSON.stringify(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])],
            ['xaxis-axisline-show_radio', false],
            ['xaxis-axisline-linestyle-color_colorpicker', '#999'],
            ['xaxis-axistick-alignwithlabel_radio', true],

        ];
        const yAxisAttrs = [
            ['yaxis-show_radio', true],
            ['yaxis-name_text', '销售额'],
            ['yaxis-nametextstyle-color_colorpicker', '#666'],
            ['yaxis-nametextstyle-fontsize_number', 12],
            ['yaxis-axislabel-color_colorpicker', '#666'],
            ['yaxis-axislabel-rotate_number', 0],
            ['yaxis-nametextstyle-fontstyle', 'normal'],
            ['yaxis-type_text', 'value'],
            ['yaxis-data_array', ''],
            ['yaxis-splitline-show_radio', false],
            ['yaxis-splitline-linestyle-type_select', 'dashed'],
            ['yaxis-splitline-linestyle-color_colorpicker', '#eee'],
            ['yaxis-axisline-show_radio', true],
            ['yaxis-axisline-linestyle-color_colorpicker', '#999']
        ];
        const legendAttrs = [
            ['legend-show_radio', true],
            ['legend-textstyle-color_colorpicker', '#666'],
            ['legend-itemstyle-color_colorpicker', 'auto'],
            ['legend-itemheight_number', 14],
            ['legend-itemwidth_number', 25],
            ['legend-bottom_number', "90%"],
            ['legend-left_number', '"50"'],
            ['legend-itemgap_number', 20],
            ['legend-textstyle-fontsize_number', 12]
        ];
        const seriesAttrs = [
            ['series-name_text', '销售额'],
            ['series-type_select', 'bar'],
            ['series-labelline-linestyle-color_colorpicker', 'transparent'],
            ['series-labelline-linestyle-width_number', 0],
            ['series-itemstyle-color_array', "#C1232B,#B5C41F,#FCCE10,#E87C25,#27727B,#FE8463"],
            ['series-itemstyle-borderradius_slider', 4],
            ['series-barmaxwidth_slider', '40%'],
            ['series-barminwidth_slider', 'auto'],
            ['series-label-bordercolor_colorpicker', 'transparent'],
            ['series-itemstyle-bordercolor_colorpicker', 'transparent'],
            ['series-showbackground_radio', false],
            ['series-backgroundstyle-opacity_slider', 0.1],
            ['series-backgroundStyle-color_colorpicker', 'rgba(180, 180, 180, 0.2)'],

            ['series-label-show_radio', true],
            ['series-label-position_select', 'top'],
            ['series-label-color_colorpicker', '#333'],
            ['series-label-fontsize_number', 12],
            ['series-label-fontweight_select', 'bold'],
            ['series-emphasis-itemstyle-shadowblur_number', 10],
            ['series-emphasis-itemstyle-shadowcolor_colorpicker', 'rgba(0, 0, 0, 0.5)'],

            ['base-data-url_text', ''],
            ['base-echart-init-script_text', ''],
        ];

        // 生成 config
        const titleConfig = buildConfig(titleAttrs);
        const gridConfig = buildConfig(gridAttrs);
        const xAxisConfig = buildConfig(xAxisAttrs);
        const yAxisConfig = buildConfig(yAxisAttrs);
        const legendConfig = buildConfig(legendAttrs);
        const seriesConfig = buildConfig(seriesAttrs);

        console.log(JSON.stringify(legendConfig))
        // 如果颜色列表只有一个颜色，扩展成默认 12 个
        if (seriesConfig.itemstyleColor.length <= 1) {
            seriesConfig.itemstyleColor = new Array(12).fill(seriesConfig.itemstyleColor[0] || 'blue');
        }

        // 调整初始大小
        this.resizeChart();
        window.addEventListener('resize', this.resizeChart.bind(this));
        if (ResizeObserver) {
            this.observer = new ResizeObserver(() => this.resizeChart());
            this.observer.observe(this.parentElement);
        }

        // 加载数据并渲染
        if (seriesConfig.dataUrl) {
            fetch(seriesConfig.dataUrl).then(res => res.json()).then(data => {
                let data_demo = data;
                if (this.getAttribute('xaxis-vertical-show_radio')?.toLowerCase() === 'true') {
                    xAxisConfig.type = 'value';
                    yAxisConfig.type = 'category';
                    xAxisConfig.data = [];
                    yAxisConfig.data = data_demo[0][Object.keys(data_demo[0])[0]].map(item => item.name);
                } else {
                    xAxisConfig.type = 'category';
                    yAxisConfig.type = 'value';
                    xAxisConfig.data = data_demo[0][Object.keys(data_demo[0])[0]].map(item => item.name);
                    yAxisConfig.data = [];
                }

                // 生成series数组（遍历所有数据组）
                const series = data_demo.map((item, index) => {
                    // 获取当前组的键名（如"销售"）
                    const key = Object.keys(item)[0];
                    // 为避免名称重复，添加索引区分（如"销售1"、"销售2"）
                    const seriesName = `${key}${index + 1}`;
                    // 当前组的数据集
                    const dataList = item[key];

                    return {
                        name: seriesName, // 系列名称（带索引区分）
                        data: dataList.map(item => item.value), // 提取value作为数据
                        type: 'bar',
                        barWidth: seriesConfig.barMinWidth,
                        barMinHeight: seriesConfig.barMaxWidth, // 注意：这里原代码可能笔误（barMinHeight用了barMaxWidth配置）
                        showBackground: seriesConfig.showBackground,
                        itemStyle: {
                            color: params => seriesConfig.itemstyleColor[params.dataIndex],
                            borderRadius: seriesConfig.itemStyleBorderRadius
                        },
                        lineStyle: {
                            color: seriesConfig.labelLineLineStyleColor,
                            width: seriesConfig.labelLineLineStyleWidth
                        },
                        backgroundStyle: {
                            color: seriesConfig.itemStyleBorderColor,
                            alpha: seriesConfig.backgroundStyleOpacity
                        },
                        label: {
                            show: seriesConfig.labelShow,
                            position: seriesConfig.labelPosition
                        }
                    };
                });

                // 同时需要确保X轴数据与所有系列的name对应（取第一组的name即可，假设各组name顺序一致）
                xAxisConfig.data = data_demo[0][Object.keys(data_demo[0])[0]].map(item => item.name);



                const option = {
                    grid: {
                        left: gridConfig.left,
                        right: gridConfig.right,
                        bottom: gridConfig.bottom,
                        top: gridConfig.top,
                        containLabel: gridConfig.containlabel,
                    },
                    title: {
                        show: titleConfig.show,
                        text: titleConfig.text,
                        left: titleConfig.left,
                        right: titleConfig.right,
                        top: titleConfig.top,
                        bottom: titleConfig.bottom,
                        textAlign: titleConfig.textalign,
                        textStyle: {
                            color: titleConfig.textstyleColor,
                            fontSize: titleConfig.textstyleFontsize,
                            fontWeight: titleConfig.textstyleFontweight,
                        },
                        subtext: titleConfig.subtext,
                        subtextStyle: {
                            color: titleConfig.subtextstyleColor,
                            fontSize: titleConfig.subtextstyleFontsize,
                            fontWeight: titleConfig.subtextstyleFontweight,
                        },
                    },
                    legend: {
                        show: legendConfig.show,
                        bottom: legendConfig.bottom,
                        left: legendConfig.left,
                        itemWidth: legendConfig.itemwidth,
                        itemHeight: legendConfig.itemheight,
                        textStyle: {
                            color: legendConfig.textstyleColor ,
                            fontSize: legendConfig.textstyleFontsize
                        },
                        itemStyle: {
                            color: legendConfig.itemstyleColor
                        },
                        itemGap: legendConfig.itemgap,
                    },
                    xAxis: {
                        show: xAxisConfig.show,
                        name: xAxisConfig.name,
                        nameTextStyle: {
                            color: xAxisConfig.nametextstyleColor,
                            fontSize: xAxisConfig.nametextstyleFontsize,
                            fontStyle: xAxisConfig.nametextstyleFontstyle,
                        },
                        type: xAxisConfig.type,
                        data: xAxisConfig.data,
                        axisLabel: {
                            color: xAxisConfig.nametextstyleColor,
                            rotate: xAxisConfig.axislabelRotate,
                            textStyle: { fontStyle: xAxisConfig.nametextstyleFontstyle }
                        },
                        axisTick: {
                            alignWithLabel: true
                        },

                    },
                    yAxis: {
                        show: yAxisConfig.show,
                        name: yAxisConfig.name,
                        type: yAxisConfig.type,
                        data: yAxisConfig.data,

                        nameTextStyle: {
                            color: yAxisConfig.nameTextStyleColor,
                            fontSize: yAxisConfig.nameTextStyleFontSize,
                            fontStyle: yAxisConfig.nameTextStyleFontStyle,
                        },
                        axisLabel: {
                            color: yAxisConfig.nameTextStyleColor,
                            rotate: yAxisConfig.axisLabelRotate,
                            textStyle: { fontStyle: yAxisConfig.nameTextStyleFontStyle }
                        },
                        splitLine: {
                            show: yAxisConfig.splitLineShow,
                            lineStyle: {
                                type: 'dashed',
                                color: '#eee'
                            }
                        },
                    },
                    series: series
                };
                console.log(JSON.stringify(option));
                this.chart.setOption(option);

            });
        }

        // 执行外部初始化脚本
        if (seriesConfig.echartInitScript) {
            try { eval(seriesConfig.echartInitScript); } catch (e) { console.error(e); }
        }
    }


    /**
     * 监听的属性
     * @returns {string[]}
     */
    static get observedAttributes() {
        return getAttributesByType('bar');
    }

    disconnectedCallback() {
        // 移除 resize 事件监听器以避免内存泄漏
        window.removeEventListener('resize', this.resizeChart.bind(this));

        // 停止观察父容器的大小变化
        if (this.observer) {
            // 停止观察
            this.observer.disconnect();
        }
        // 清除定时器以避免内存泄漏
        clearInterval(this.timerId);
    }
    // 定时器
    setTimer(interval) {
        // 清除之前的定时器
        clearInterval(this.timerId);
        // 创建新的定时器
        if (interval > 0){
            console.log(interval.toString()+'sgc.................');
            // 设置新的定时器
            this.timerId = setInterval(() => {
                this.executeScript();
            }, interval);
        }

    }
    executeScript(){
        if (this.echarttimerscript != ""){
            try {
                eval(this.echarttimerscript);
            } catch (error) {
                console.log(error.message);
            }
        }
        else{
            console.log("no script to execute");
        }

    }
    // 监听容器大小变化并重新调整图表
    resizeChart() {
        // 调整图表大小
        this.chart.resize();
    }
    // 提供一个方法来获取 ECharts 实例
    getChartInstance() {
        return this.chart;
    }
    // 更新数据
    async updateData(dataurl) {
        try {
            const fullUrl = dataurl;
            const response = await fetch(fullUrl);
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            const data = await response.json();

            // 获取当前图表配置并创建副本，避免直接修改源配置
            const currentOption = JSON.parse(JSON.stringify(this.chart.getOption()));
            // 确保series数组存在且为新数组（避免引用问题）
            currentOption.series = currentOption.series ? [...currentOption.series] : [];

            if (data && Array.isArray(data) && data.length > 0) {
                // 1. 解析新数据
                const newSeriesList = [];
                data.forEach(item => {
                    Object.entries(item).forEach(([seriesName, dataItems]) => {
                        if (Array.isArray(dataItems)) {
                            newSeriesList.push({
                                name: seriesName,
                                data: dataItems.map(item => item.value),
                                xData: dataItems.map(item => item.name)
                            });
                        }
                    });
                });

                // 2. 处理X轴数据
                if (newSeriesList.length > 0 && newSeriesList[0].xData &&
                    currentOption.xAxis && currentOption.xAxis.length > 0) {
                    currentOption.xAxis[0].data = newSeriesList[0].xData;
                }

                // 3. 处理系列数据 - 保留原始样式配置
                currentOption.series = []; // 先清空所有现有系列
                newSeriesList.forEach((newSeries, index) => {
                    // 完全获取原有系列的配置（包括样式、类型等所有属性）
                    // 如果是第一个系列且存在原有配置，则使用原有配置作为基础
                    // 否则使用最后一个已有系列配置作为基础，或创建默认配置
                    let baseSeries = {};
                    const originalSeries = this.chart.getOption().series || [];

                    if (originalSeries.length > 0) {
                        // 优先使用同索引的原有配置，如果不存在则使用最后一个配置
                        baseSeries = originalSeries[index] || originalSeries[originalSeries.length - 1];
                    } else {
                        // 没有原有配置时使用默认配置
                        baseSeries = {
                            type: 'bar',
                            itemStyle: { color: '#5470c6' },
                            label: { show: false }
                        };
                    }

                    // 创建新系列，保留所有原有配置，仅更新名称和数据
                    currentOption.series.push({
                        ...JSON.parse(JSON.stringify(baseSeries)), // 深拷贝避免引用问题
                        name: newSeries.name,
                        data: newSeries.data
                    });
                });
            } else {
                // 没有数据时完全清空系列
                currentOption.series = [];
                // 清空X轴数据
                if (currentOption.xAxis && currentOption.xAxis.length > 0) {
                    currentOption.xAxis[0].data = [];
                }
            }

            // 4. 强制刷新图表配置
            this.chart.setOption(currentOption);
        } catch (error) {
            console.log(`错误: ${error.message}`);
        }
    }





    // 属性变化监听的时候调用
    attributeChangedCallback(name, oldValue, newValue) {
        // if (name && newValue){
        if (name){
            switch (name) {
                //上面是标题的属性，
                case 'title-show_radio':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        const showBool = newValue === "true";
                        // 更新X轴数据
                        currentOptions.title[0].show = showBool;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'title-text_text':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        // 更新X轴数据
                        currentOptions.title[0].text = newValue;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);

                    }
                    break;
                case 'title-textstyle-color_colorpicker':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        // 更新X轴数据
                        currentOptions.title[0].textStyle.color = newValue;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);

                    }
                    break;
                case 'title-textstyle-fontsize_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        // 更新X轴数据
                        currentOptions.title[0].textStyle.fontSize = newValue;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'title-textstyle-fontweight_select':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        // 更新X轴数据
                        currentOptions.title[0].textStyle.fontWeight = newValue;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);

                    }
                    break;
                case 'title-textStyle-fontStyle_select':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        // 更新X轴数据
                        currentOptions.title[0].textStyle.fontStyle = newValue;
                    }
                    break;
                case 'title-subtext_text':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        // 更新X轴数据
                        currentOptions.title[0].subtext = newValue;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'title-subtextstyle-color_colorpicker':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        // 更新X轴数据
                        currentOptions.title[0].subtextStyle.color = newValue;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'title-subtextstyle-fontsize_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        // 更新X轴数据
                        currentOptions.title[0].subtextStyle.fontSize = newValue;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'title-subtextstyle-fontweight_select':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        // 更新X轴数据
                        currentOptions.title[0].subtextStyle.fontWeight = newValue;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'title-left_slider':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        // 更新
                        currentOptions.title[0].left = `${newValue}%`;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'title-top_slider':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        //
                        currentOptions.title[0].top = `${newValue}%`;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'title-right_slider':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.title[0].right = `${newValue}%`;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'title-bottom_slider':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.title[0].bottom = `${newValue}%`;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'title-itemgap_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.title[0].itemGap = newValue;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'title-textalign_select':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.title[0].textAlign = newValue;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'grid-left_slider':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.grid[0].left = `${newValue}%`;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'grid-right_slider':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.grid[0].right = `${newValue}%`;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'grid-bottom_slider':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.grid[0].bottom = `${newValue}%`;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'grid-top_slider':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.grid[0].top = `${newValue}%`;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;

                case 'xaxis-show_radio':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        // 更新X轴数据
                        const hideXBoolean = newValue === "true";
                        currentOptions.xAxis[0].show = hideXBoolean;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'xaxis-axislabel-show_radio':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.xAxis[0].axisLabel.show = newValue;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'xaxis-max_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.xAxis[0].max = newValue;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'xaxis-min_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.xAxis[0].min = newValue;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'xaxis-position_select':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.xAxis[0].position = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'xaxis-offset_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.xAxis[0].offset = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'xaxis-nametextstyle-color_colorpicker':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.xAxis[0].nameTextStyle.color = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'xaxis-nametextstyle-fontsize_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.xAxis[0].nameTextStyle.fontSize = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'xaxis-nametextstyle-fontweight_select':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.xAxis[0].nameTextStyle.fontWeight = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'xaxis-nametextstyle-fontstyle_select':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.xAxis[0].nameTextStyle.fontStyle = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'xaxis-axislabel-color_colorpicker':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.xAxis[0].axisLabel.color = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'xaxis-inverse_radio':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.xAxis[0].inverse = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'xaxis-name_text':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.xAxis[0].name = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'xaxis-axislabel-rotate_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        // 更新X轴数据
                        currentOptions.xAxis[0].axisLabel.rotate = newValue;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'xaxis-vertical-show_radio':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions) {
                        const isVertical = newValue === 'true';

                        // 获取原始类目数据
                        let categories = [];
                        if (isVertical) {
                            categories = currentOptions.xAxis?.[0]?.data || [];
                        } else {
                            categories = currentOptions.yAxis?.[0]?.data || [];
                        }

                        // 获取当前数据（销量等）
                        const seriesData = currentOptions.series?.[0]?.data || [];

                        if (isVertical) {
                            // 转为纵向
                            currentOptions.xAxis[0].type = 'value';
                            currentOptions.yAxis[0].type = 'category';
                            currentOptions.xAxis[0].data = [];
                            currentOptions.yAxis[0].data = categories;
                        } else {
                            // 转为横向
                            currentOptions.xAxis[0].type = 'category';
                            currentOptions.yAxis[0].type = 'value';
                            currentOptions.xAxis[0].data = categories;
                            currentOptions.yAxis[0].data = [];
                        }

                        // 设置新的配置
                        this.chart.setOption(currentOptions, true);
                    }
                    break;
                case 'xaxis-splitline-show_radio':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        newValue = newValue == "true";
                        currentOptions.xAxis[0].splitLine.show = newValue;
                        // 配置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break
                case 'series-itemstyle-color_array':
                    var currentOptions = this.chart.getOption();
                    var newValue_array = newValue.split(",");
                    if (currentOptions && newValue_array.length>0){
                        if (currentOptions.series.length > 0){
                            // 更新颜色配置
                            currentOptions.series[0].itemStyle.color = function(params) {
                                return newValue_array[params.dataIndex];
                            };
                            // 设置新的选项
                            this.chart.setOption(currentOptions);
                        }

                    }

                    break;

                case 'series-label-fontsize_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.series[0].label.fontSize = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'series-label-fontweight_select':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.series[0].label.fontWeight = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'series-emphasis-itemstyle-shadowblur_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.series[0].emphasis.itemStyle.shadowBlur = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'series-emphasis-itemstyle-shadowcolor_colorpicker':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.series[0].emphasis.itemStyle.shadowColor = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'yaxis-show_radio':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        newValue = newValue == "true";
                        currentOptions.yAxis[0].axisLabel.show = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'yaxis-axislabel-show_radio':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        newValue = newValue == "true";
                        currentOptions.yAxis[0].axisLabel.show = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'yaxis-max_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.yAxis[0].max = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'yaxis-min_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.yAxis[0].min = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'yaxis-position_select':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.yAxis[0].position = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'yaxis-offset_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.yAxis[0].offset = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'yaxis-nametextstyle-color_colorpicker':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.yAxis[0].nameTextStyle.color = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'yaxis-nametextstyle-fontsize_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.yAxis[0].nameTextStyle.fontSize = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'yaxis-nametextstyle-fontweight_select':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.yAxis[0].nameTextStyle.fontWeight = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'yaxis-nametextstyle-fontstyle':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.yAxis[0].nameTextStyle.fontStyle = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'yaxis-axislabel-color_colorpicker':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.yAxis[0].axisLabel.color = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'yaxis-axislabel-rotate_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.yAxis[0].axisLabel.rotate = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'yaxis-name_text':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.yAxis[0].name = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'yaxis-splitline-show_radio':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        newValue = newValue == "true";
                        currentOptions.yAxis[0].splitLine.show = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                /*
                * 下面是图例相关属性
                * */
                case 'legend-show_radio':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        const showBool = newValue === "true";
                        // 图例的显示
                        currentOptions.legend[0].show = showBool;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'legend-textstyle-color_colorpicker':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        // 更新X轴数据
                        currentOptions.legend[0].textStyle.color = newValue;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);

                    }
                    break;
                case 'legend-textstyle-fontsize_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        // 获取当前值
                        currentOptions.legend[0].textStyle.fontSize = newValue;
                        // 获取当前值
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'legend-textstyle-fontweight_select':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.legend[0].textStyle.fontWeight = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'legend-textstyle-fontstyle_select':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.legend[0].textStyle.fontStyle = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'legend-itemstyle-color_colorpicker':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        // 更新X轴数据
                        currentOptions.legend[0].itemStyle.color = newValue;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'legend-itemheight_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions && currentOptions.legend && currentOptions.legend[0]) {
                        // 仅更新图例图标的高度
                        currentOptions.legend[0].itemHeight = parseInt(newValue);
                        this.chart.setOption(currentOptions);
                    }
                    break;

                case 'legend-itemwidth_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions && currentOptions.legend && currentOptions.legend[0]) {
                        // 仅更新图例图标的宽度
                        currentOptions.legend[0].itemWidth = parseInt(newValue);
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'legend-bottom_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        // 仅更新图例图标的宽度
                        currentOptions.legend[0].bottom = `${newValue}%`;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'legend-top_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.legend[0].top = `${newValue}%`;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'legend-right_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.legend[0].right = `${newValue}%`;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'legend-left_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.legend[0].left = `${newValue}%`;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'legend-itemgap_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.legend[0].itemGap = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                // 下面是柱状体的属性
                case 'series-barmaxwidth_slider':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        // 更新柱状体的宽度
                        currentOptions.series[0].barWidth = newValue;
                        // 设置新的选项
                        this.chart.setOption(currentOptions);
                    }
                    break ;
                case 'series-bargap_text':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.series[0].barGap = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break ;
                case 'series-barminwidth_slider':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions) {
                        if (currentOptions.series && currentOptions.series.length > 0) {
                            currentOptions.series[0].barMinWidth = parseInt(newValue) || 0; // 设置柱状图最小高度
                            this.chart.setOption(currentOptions);
                        }
                    }
                    break;
                case 'series-showbackground_radio':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions && currentOptions.series && currentOptions.series.length > 0) {
                        const show = newValue === true || newValue === 'true'; // 解析布尔值
                        if (!currentOptions.series[0].itemStyle) currentOptions.series[0].itemStyle = {};

                        if (!currentOptions.series[0].backgroundStyle) {
                            currentOptions.series[0].backgroundStyle = {
                                color: 'rgba(220, 220, 220, 0.3)' // 默认背景色
                            };
                        }

                        currentOptions.series[0].showBackground = show;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'series-backgroundstyle-color_colorpicker':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions && currentOptions.series && currentOptions.series.length > 0) {
                        if (!currentOptions.series[0].backgroundStyle) {
                            currentOptions.series[0].backgroundStyle = {};
                        }

                        // 保留之前的透明度 alpha 设置
                        const alpha = currentOptions.series[0].backgroundStyle.alpha || 1;
                        currentOptions.series[0].backgroundStyle.color = hexToRgba(newValue, alpha);
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'series-backgroundstyle-borderwidth_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.series[0].backgroundStyle.borderWidth = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'series-backgroundstyle-bordertype_select':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.series[0].backgroundStyle.borderType = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'series-backgroundstyle-opacity_slider':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions && currentOptions.series && currentOptions.series.length > 0) {
                        if (!currentOptions.series[0].backgroundStyle) {
                            currentOptions.series[0].backgroundStyle = {};
                        }

                        // 如果之前设置过颜色，取出再更新透明度
                        const prevColor = currentOptions.series[0].backgroundStyle.color || 'rgba(220,220,220,0.3)';
                        const rgb = extractRgbFromRgba(prevColor); // 从旧的 rgba 提取 rgb
                        const alpha = parseFloat(newValue);

                        currentOptions.series[0].backgroundStyle.color = `rgba(${rgb}, ${alpha})`;
                        currentOptions.series[0].backgroundStyle.opacity = alpha; // 存储用于再次设置时使用
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'series-labelline-linestyle-width_number':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.series[0].labelLine.lineStyle.width = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'series-label-show_radio':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        newValue = newValue === true || newValue === 'true';
                        currentOptions.series[0].label.show = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'series-label-position_select':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.series[0].label.position = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'series-label-bordercolor_colorpicker':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.series[0].label.borderColor = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'series-itemstyle-bordercolor_colorpicker':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.series[0].itemStyle.borderColor = newValue;
                    }
                    break;
                case 'series-itemstyle-borderradius_slider':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.series[0].itemStyle.borderRadius = parseInt(newValue);
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'series-label-color_colorpicker':
                    var currentOptions = this.chart.getOption();
                    if (currentOptions){
                        currentOptions.series[0].label.color = newValue;
                        this.chart.setOption(currentOptions);
                    }
                    break;
                case 'base-echart-timer':
                    if (oldValue !== newValue) {
                        if (newValue != ""){
                            this.setTimer(parseInt(newValue)*1000);
                        }
                    }
                    break;
                case 'base-echart-timer-script':
                    if (this.echarttimerscript == ""){
                        clearInterval(this.timerId)
                    }
                    else{
                        this.setTimer(parseInt(this.echarttimer)*1000);
                    }
                    break;
                case 'base-echart-init-script':
                    if (this.echartinitscript != ""){
                        try {
                            eval(this.echartinitscript);
                        } catch (error) {
                            console.log(error.message);
                        }

                    }
                    break;
                case 'base-data-url_text':
                    this.updateData(newValue);
                    break;
            }
        }

    }
}

// 定义新的 HTML 元素
customElements.define('chart-component', ChartComponent);

// hex 转 rgba
function hexToRgba(hex, alpha) {
    let r = 0, g = 0, b = 0;

    if (hex.length === 4) {
        r = "0x" + hex[1] + hex[1];
        g = "0x" + hex[2] + hex[2];
        b = "0x" + hex[3] + hex[3];
    } else if (hex.length === 7) {
        r = "0x" + hex[1] + hex[2];
        g = "0x" + hex[3] + hex[4];
        b = "0x" + hex[5] + hex[6];
    }
    return "rgba(" + +r + "," + +g + "," + +b + "," + alpha + ")";
}

// 提取 rgb，不含透明度
function extractRgbFromRgba(rgbaStr) {
    const result = rgbaStr.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
    if (result) {
        return `${result[1]}, ${result[2]}, ${result[3]}`;
    }
    return "220, 220, 220"; // 默认灰色
}


/**
 * 判断给定的属性值是否为true字符串
 * @param {string} attrVal - 要检查的属性值
 * @returns {boolean} 当属性值存在且转换为小写后等于'true'时返回true，否则返回false
 */
function isTrue(attrVal) {
    // 检查属性值是否存在且转换为小写后等于'true'
    return attrVal && attrVal.toLowerCase() === 'true';
}
